import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int[] dx = {0, 0, 1, -1};
    public int[] dy = {1, -1, 0, 0};
    public int nearestExit(char[][] maze, int[] entrance) {
        // 先找出口， 确定都有哪几个出口
        int m = maze.length;
        int n = maze[0].length;
        boolean[][] vis = new boolean[m][n];
        int step = 0;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(entrance);
        int a = entrance[0];
        int b = entrance[1];
        vis[a][b] = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            step++;
            while(size > 0){
                int[] piont = queue.poll();
                int p1 = piont[0];
                int p2 = piont[1];
                for(int i = 0; i < 4; i++){
                    int x = p1 + dx[i];
                    int y = p2 + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.' && !vis[x][y]){
                        queue.offer(new int[] {x, y});
                        vis[x][y] = true;
                        if(x == 0 || x == m - 1 || y == 0 || y == n - 1){
                            return step;
                        }
                    }
                }
                size--;
            }
        }
        return -1;
    }
}